#!/usr/bin/env python
    #, 

from optparse import OptionParser
import time
import traceback
import amqplib.client_0_8 as amqp
import cometdemo.other.json as json

import cometdemo.greed.db as db
from cometdemo.greed.db import mc
from cometdemo.greed.broker import send_amqp_message

import docutils
import rest_pygments


def callback(msg):
    key = msg.body

    version, content = db.get(key)
    if content.__hash__() != mc.get('%s.output.inputhash' % (key,)):
        print '[*] %r #%r ___ start' % (key,version)
        t0 = time.time()
        try:
            output = docutils.core.publish_string(
                    source=content,
                    settings_overrides={'file_insertion_enabled': 0, 'raw_enabled': 0},
                    writer_name='html')
        except:
            output = (str(traceback.format_exc()).strip()).replace('\n', '<br>')
            print output

        t1 = time.time()
        mc.set('%s.output' % (key,), output)
        mc.set('%s.output.inputhash' % (key,), content.__hash__())

        print '[*] %r #%r ^^^ done in %9.3f.ms '  % (key, version, (t1-t0)*1000.0,)
        send_amqp_message(key, 'newoutput')
    else:
        print '[*] %r cached '  % (key)

    msg.channel.basic_ack(msg.delivery_tag)



def main():
    conn = amqp.Connection('localhost', userid='guest', password='guest')

    ch = conn.channel()
    ch.access_request('/data', active=True, read=True)
    ch.exchange_declare('render', 'fanout', auto_delete=False)
    qname, _, _ = ch.queue_declare('default_render', auto_delete=False)
    ch.queue_bind(qname, 'render')
    ch.basic_consume(qname, callback=callback)

    print "[*] sztarten"
    while ch.callbacks:
        ch.wait()

    ch.close()
    conn.close()

if __name__ == '__main__':
    main()

